﻿using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations.Schema;
using System.Data.Entity;
using System.Data.Entity.Core.Mapping;
using System.Data.Entity.Core.Metadata.Edm;
using System.Data.Entity.Core.Objects;
using System.Data.Entity.Infrastructure;
using System.Data.Entity.Infrastructure.DependencyResolution;
using System.Data.Entity.Infrastructure.Pluralization;
using System.Data.Entity.ModelConfiguration;
using System.Data.Entity.ModelConfiguration.Conventions;
using System.Data.Entity.Validation;
using System.Linq;
using System.Runtime.Serialization;
using System.Text.RegularExpressions;
using System.Threading;
using System.Threading.Tasks;
using WinnerCMS.Common;
using WinnerCMS.Common.Extension;
using WinnerCMS.Data.Migrations;
using WinnerCMS.Model;
using Task = WinnerCMS.Model.Task;

namespace WinnerCMS.Data
{
    public partial class Entities
        : DbContext
    {
        static Entities()
        {
        }

        public Entities()
            : base("Name=Entities")
        {

        }


        public DbSet<Advert> AdLists { get; set; }
        public DbSet<Annex> Annex { get; set; }
        public DbSet<Announce> Announces { get; set; }
        public DbSet<Area> Areas { get; set; }
        public DbSet<Article> Articles { get; set; }
        public DbSet<Core> Cores { get; set; }
        public DbSet<Bank> Banks { get; set; }
        public DbSet<BankrollList> BankrollList { get; set; }
        public DbSet<Brand> Brands { get; set; }
        public DbSet<Business> Business { get; set; }
        public DbSet<Category> Categoryes { get; set; }
        public DbSet<WinnerCMS.Model.Model> Models { get; set; }

        public DbSet<User> Users { get; set; }
        public DbSet<Comment> Comments { get; set; }
        public DbSet<Consultant> Consultants { get; set; }
        public DbSet<ContentKeyWord> ContentKeyWords { get; set; }
        public DbSet<ContentProperty> ContentPropertes { get; set; }
        public DbSet<CounterContent> CounterContents { get; set; }
        public DbSet<CounterDiary> CounterDiares { get; set; }
        public DbSet<Delivery> Deliveres { get; set; }
        public DbSet<DeliveryArea> DeliveryAreas { get; set; }
        public DbSet<DeliveryMethod> DeliveryMethods { get; set; }
        public DbSet<Digg> Diggs { get; set; }
        public DbSet<DiggDiary> DiggDiares { get; set; }
        public DbSet<ExtensionCategory> ExtensionCategores { get; set; }
        public DbSet<ExtensionCategoryList> ExtensionCategoryList { get; set; }
        public DbSet<Favorite> Favorites { get; set; }
        public DbSet<Field> Fields { get; set; }
        public DbSet<FriendLink> FriendLinks { get; set; }
        public DbSet<Gather> Gathers { get; set; }
        public DbSet<GatherHistory> GatherHistores { get; set; }
        public DbSet<GatherUrlCache> GatherUrlCaches { get; set; }
        public DbSet<GoodsCustomField> GoodsCustomFields { get; set; }
        public DbSet<GoodsCustomFieldValue> GoodsCustomFieldValues { get; set; }
        public DbSet<GoodsPart> GoodsParts { get; set; }
        public DbSet<GuestBook> GuestBooks { get; set; }
        public DbSet<Help> Helps { get; set; }
        public DbSet<HotKeyWord> HotKeyWords { get; set; }
        public DbSet<Invoice> Invoices { get; set; }
        public DbSet<IPBlackList> IPBlackList { get; set; }
        public DbSet<Log> Logs { get; set; }
        public DbSet<Memu> Memus { get; set; }
        public DbSet<Message> Messages { get; set; }
        public DbSet<OrderList> OrderList { get; set; }
        public DbSet<Order> Orders { get; set; }
        public DbSet<PaymentMethod> PaymentMethods { get; set; }
        public DbSet<Photo> Photos { get; set; }
        public DbSet<PhotoList> PhotoList { get; set; }
        public DbSet<PriceChange> PriceChanges { get; set; }
        public DbSet<Right> Rights { get; set; }
        public DbSet<Role> Roles { get; set; }
        public DbSet<SecurityCenter> SecurityCenters { get; set; }
        public DbSet<Goods> Goods { get; set; }
        public DbSet<GoodsImg> GoodsImgs { get; set; }
        public DbSet<ShoppingCart> ShoppingCarts { get; set; }
        public DbSet<Soft> Softs { get; set; }
        public DbSet<SoftDownList> SoftDownList { get; set; }
        public DbSet<SoftServer> SoftServers { get; set; }
        public DbSet<SoftLinkErr> SoftLinkErrs { get; set; }
        public DbSet<Special> Specials { get; set; }
        public DbSet<Tag> Tags { get; set; }
        public DbSet<Task> Tasks { get; set; }
        public DbSet<TaskActive> TaskActives { get; set; }
        public DbSet<Template> Templates { get; set; }
        public DbSet<UDT> UDTs { get; set; }
        public DbSet<Unit> Units { get; set; }
        public DbSet<UserAddress> UserAddres { get; set; }
        public DbSet<UserMoney> UserMoney { get; set; }
        public DbSet<UserScore> UserScores { get; set; }
        public DbSet<Vote> Votes { get; set; }
        public DbSet<VoteChoice> VoteChoices { get; set; }
        public DbSet<Words> Words { get; set; }


        protected override void OnModelCreating(DbModelBuilder modelBuilder)
        {
            modelBuilder.Properties<decimal>().Configure(x => x.HasPrecision(18, 4));
            modelBuilder.Properties<string>().Configure(x => x.HasMaxLength(50).IsUnicode(true));
            modelBuilder.Properties().Where(x => x.Name == "Id").Configure(x => x.HasColumnOrder(0));

            modelBuilder.Conventions.AddAfter<PluralizingTableNameConvention>(new CMSTableConvention());
            //modelBuilder.Conventions.Remove<OneToManyCascadeDeleteConvention>();
            //modelBuilder.Conventions.Remove<OneToOneConstraintIntroductionConvention>();
            //modelBuilder.Conventions.Remove<ManyToManyCascadeDeleteConvention>();

            modelBuilder.Properties().Where(x => x.GetCustomAttributes(false).OfType<NonUnicode>().Any()).Configure(c => c.IsUnicode(false));

            modelBuilder.Configurations.AddFromAssembly(typeof(Entities).Assembly);
        }

        #region 测试数据库连接是否成功。
        /// <summary>
        /// 测试数据库连接是否成功。
        /// </summary>
        /// <returns></returns>
        public bool TestConnection(string connectionString)
        {
            using (Entities db = new Entities())
            {
                try
                {
                    db.Database.Connection.ConnectionString = connectionString;
                    db.Database.Connection.Open();
                    db.Database.Connection.Close(); return true;
                }
                catch
                {
                    return false;
                }
            }
        }
        #endregion

        #region override

        public override int SaveChanges()
        {
            try
            {
                return base.SaveChanges();
            }
            catch (System.Data.Entity.Infrastructure.DbUpdateException ex)
            {
                throw new Exception(ex.Message);
            }
            catch (System.Data.Entity.Validation.DbEntityValidationException ex)
            {
                throw new Exception(ex.DbEntityValidationResultToString());
            }
        }

        public override Task<int> SaveChangesAsync()
        {
            try
            {
                return base.SaveChangesAsync();
            }
            catch (DbUpdateException ex)
            {
                throw new Exception(ex.Message);
            }
            catch (DbEntityValidationException ex)
            {
                throw new Exception(ex.DbEntityValidationResultToString());
            }
        }

        public override Task<int> SaveChangesAsync(CancellationToken cancellationToken)
        {
            try
            {
                return base.SaveChangesAsync(cancellationToken);
            }
            catch (DbUpdateException ex)
            {
                throw new Exception(ex.Message);
            }
            catch (DbEntityValidationException ex)
            {
                throw new Exception(ex.DbEntityValidationResultToString());
            }
        } 
        #endregion
    }
}